<?php

namespace SinoPHP\BbdBoss\Api;

use InvalidArgumentException;
use Upfor\UpforPHP\Library\Math;

/**
 * Cache刷新系统所需关联关系
 *
 * 用于给Cache刷新/预缓存系统提供[域名-主机-机房-分控]之间的关联关系
 */
class CacheSystemRelation extends ApiAbstract {

    /**
     * @var \SinoPHP\BbdBoss\Model\CacheSystemRelation
     */
    protected $cacheSystemRelation;

    public function v_1_0_0() {
        $this->cacheSystemRelation = model('CacheSystemRelation');

        // 分控所有IP信息
        $subControlIpList = $this->cacheSystemRelation->getSubControlServerIpList($this->cacheSystemRelation->subControlRoleId);
        if (empty($subControlIpList)) {
            $this->success([]);
        }

        $subControlIps = array_column($subControlIpList, 'ip');
        $subControlAreas = array_column($subControlIpList, 'server_area');

        $bindIpList = $this->cacheSystemRelation->getBindIpList([
            'server_area' => $subControlAreas,
            'ip|!' => $subControlIps,
            'ip_type' => [2, 3], // 仅真实IP或单一IP
            'is_delete' => 0,
        ]);

        $bindIpIds = array_column($bindIpList, 'ip_id');
        list($bindGroupList, $bindGroupIds) = $this->cacheSystemRelation->getRefGroupListByBindIp($bindIpIds);

        $bindDomainList = $this->cacheSystemRelation->getDomainListByBindGroup($bindGroupIds);

        $refList = array();
        foreach ($bindIpList as $row) {
            if (empty($refList[$row['server_area']][$row['ip']])) {
                $refList[$row['server_area']][$row['ip']] = $ipUnit = array(
                    'status' => $row['status'] == 0 ? 0 : 1,
                    'domainList' => array(),
                );
            } else {
                $ipUnit = $refList[$row['server_area']][$row['ip']];
            }

            if (!empty($bindGroupList[$row['ip_id']]) && is_array($bindGroupList[$row['ip_id']])) {
                $ipGroupIds = $bindGroupList[$row['ip_id']];
                foreach ((array) $ipGroupIds as $gid) {
                    !empty($bindDomainList[$gid]) && $ipUnit['domainList'] = array_merge($ipUnit['domainList'], (array) $bindDomainList[$gid]);
                }

                // 域名去重
                $ipUnit['domainList'] = array_values(array_unique($ipUnit['domainList']));
                $refList[$row['server_area']][$row['ip']] = $ipUnit;
            }

            // 去除无域名绑定的IP
            if (empty($ipUnit['domainList'])) {
                unset($refList[$row['server_area']][$row['ip']]);
            }
        }

        // 关联分控&Cache域名
        $data = array();
        foreach ($subControlIpList as $row) {
            if (!empty($refList[$row['server_area']])) {
                $data[$row['ip']] = $refList[$row['server_area']];
            }
        }

        $this->success($data);
    }

}
